﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.Sockets;
using Windows.Security.Cryptography;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

namespace 面向群智感知应用的匿名激励系统服务端UWP
{
    //TODO: Consider load the details asyncronisly. Try to load the data in a Distpacher.
    //TODO: Consider PLM

    public sealed partial class MasterDetailSelection : Page
    {
        private 用户 selectedContact;

        private ObservableCollection<用户> Contacts;
        private StreamSocketListener 文字监听器 = new StreamSocketListener();

        public MasterDetailSelection()
        {
            this.InitializeComponent();
            this.Loaded += OnLoaded;

            // Get the contacts from a Service
            // Remember to enable the NavigationCacheMode of this Page to avoid
            // load the data every time user navigates back and forward.
            Contacts = 用户.用户列表;
            //if (Contacts.Count > 0)
            {
                MasterListView.ItemsSource = Contacts;
            }
            监听();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Details view can remove an item from the list.
            if (e.Parameter as string == "Delete")
            {
                DeleteItem(null, null);
            }
            base.OnNavigatedTo(e);
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            if (selectedContact == null && Contacts.Count > 0)
            {
                selectedContact = Contacts[0];
                MasterListView.SelectedIndex = 0;
            }
            // If the app starts in narrow mode - showing only the Master listView -
            // it is necessary to set the commands and the selection mode.
            if (PageSizeStatesGroup.CurrentState == NarrowState)
            {
                VisualStateManager.GoToState(this, MasterState.Name, true);
            }
            else if (PageSizeStatesGroup.CurrentState == WideState)
            {
                // In this case, the app starts is wide mode, Master/Details view,
                // so it is necessary to set the commands and the selection mode.
                VisualStateManager.GoToState(this, MasterDetailsState.Name, true);
                MasterListView.SelectionMode = ListViewSelectionMode.Extended;
                MasterListView.SelectedItem = selectedContact;
            }
            else
            {
                new InvalidOperationException();
            }
        }

        private void OnCurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            bool isNarrow = e.NewState == NarrowState;
            if (isNarrow)
            {
                Frame.Navigate(typeof(DetailsPage), selectedContact, new SuppressNavigationTransitionInfo());
            }
            else
            {
                VisualStateManager.GoToState(this, MasterDetailsState.Name, true);
                MasterListView.SelectionMode = ListViewSelectionMode.Extended;
                MasterListView.SelectedItem = selectedContact;
            }

            EntranceNavigationTransitionInfo.SetIsTargetElement(MasterListView, isNarrow);
            if (DetailContentPresenter != null)
            {
                EntranceNavigationTransitionInfo.SetIsTargetElement(DetailContentPresenter, !isNarrow);
            }
        }

        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PageSizeStatesGroup.CurrentState == WideState)
            {
                if (MasterListView.SelectedItems.Count == 1)
                {
                    selectedContact = MasterListView.SelectedItem as 用户;
                    EnableContentTransitions();
                }
                // Entering in Extended selection
                else if (MasterListView.SelectedItems.Count > 1
                     && MasterDetailsStatesGroup.CurrentState == MasterDetailsState)
                {
                    VisualStateManager.GoToState(this, ExtendedSelectionState.Name, true);
                }
            }
            // Exiting Extended selection
            if (MasterDetailsStatesGroup.CurrentState == ExtendedSelectionState &&
                MasterListView.SelectedItems.Count == 1)
            {
                VisualStateManager.GoToState(this, MasterDetailsState.Name, true);
            }


            DataContext = selectedContact;

        }

        // ItemClick event only happens when user is a Master state. In this state,
        // selection mode is none and click event navigates to the details view.
        private void OnItemClick(object sender, ItemClickEventArgs e)
        {
            // The clicked item it is the new selected contact
            selectedContact = e.ClickedItem as 用户;
            if (PageSizeStatesGroup.CurrentState == NarrowState)
            {
                // Go to the details page and display the item
                Frame.Navigate(typeof(DetailsPage), selectedContact, new DrillInNavigationTransitionInfo());
            }
            //else
            {
                // Play a refresh animation when the user switches detail items.
                //EnableContentTransitions();
            }
        }

        private void EnableContentTransitions()
        {
            DetailContentPresenter.ContentTransitions.Clear();
            DetailContentPresenter.ContentTransitions.Add(new EntranceThemeTransition());
        }

        #region Commands

        private void DeleteItem(object sender, RoutedEventArgs e)
        {
            if (selectedContact != null)
            {
                Contacts.Remove(selectedContact);

                if (MasterListView.Items.Count > 0)
                {
                    MasterListView.SelectedIndex = 0;
                    selectedContact = MasterListView.SelectedItem as 用户;
                }
                else
                {
                    // Details view is collapsed, in case there is not items.
                    DetailContentPresenter.Visibility = Visibility.Collapsed;
                    selectedContact = null;
                }
            }
        }

        private void SelectItems(object sender, RoutedEventArgs e)
        {
            if (MasterListView.Items.Count > 0)
            {
                VisualStateManager.GoToState(this, MultipleSelectionState.Name, true);
            }
        }

        private void CancelSelection(object sender, RoutedEventArgs e)
        {
            if (PageSizeStatesGroup.CurrentState == NarrowState)
            {
                VisualStateManager.GoToState(this, MasterState.Name, true);
            }
            else
            {
                VisualStateManager.GoToState(this, MasterDetailsState.Name, true);
            }
        }

        private void ShowSliptView(object sender, RoutedEventArgs e)
        {
            // Clearing the cache
            int cacheSize = ((Frame)Parent).CacheSize;
            ((Frame)Parent).CacheSize = 0;
            ((Frame)Parent).CacheSize = cacheSize;

            MySamplesPane.SamplesSplitView.IsPaneOpen = !MySamplesPane.SamplesSplitView.IsPaneOpen;
        }

        #endregion Commands

        private async void 获取文字事件(StreamSocketListener sender,
    StreamSocketListenerConnectionReceivedEventArgs args)
        {
            int num = -1;
            try
            {
                //Read line from the remote client.
                Stream inStream = args.Socket.InputStream.AsStreamForRead();
                StreamReader reader = new StreamReader(inStream);
                num = int.Parse(await reader.ReadLineAsync());
                /*await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                {
                    Contacts[num].温度 = double.Parse(await reader.ReadLineAsync());
                    Contacts[num].湿度 = double.Parse(await reader.ReadLineAsync());
                    Contacts[num].气压 = double.Parse(await reader.ReadLineAsync());
                    Contacts[num].光照强度 = double.Parse(await reader.ReadLineAsync());
                });*/
              
                Debug.WriteLine("成功收到" + num + "号信息");
                //Send the line back to the remote client.
                /*Stream outStream = args.Socket.OutputStream.AsStreamForWrite();
                StreamWriter writer = new StreamWriter(outStream, new UTF8Encoding(false));
                await writer.WriteLineAsync(Contacts[num].request);
                if (Contacts[num].request != "Success")
                    Contacts[num].request = "Success";
                await writer.FlushAsync();*/
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                文字监听器.ConnectionReceived += 获取文字事件;
            }
        }


        private async Task 监听()
        {
            await Task.Run(async () =>
            {
                try
                {
                    //Create a StreamSocketListener to start listening for TCP connections.

                    文字监听器.ConnectionReceived += 获取文字事件;
                    await 文字监听器.BindServiceNameAsync("1337");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    //Handle exception.
                }
            });
        }

        private void btn1_Click(object sender, RoutedEventArgs e)
        {
            Contacts.Add(new 用户(null));
        }
    }
}